//返回的response中的json数据解压方法-->unzip
function unzip(b64Data){
	var strData = atob(b64Data);
	// 将二进制字符串转换为字符数组
	var charData  = strData.split('').map(function(x){return x.charCodeAt(0);});
	// 将数字数组转换为字节数组
	var binData = new Uint8Array(charData);
	// unzip
	var data  = pako.inflate(binData);
	// gunzipped ByteArray返回ASCII字符串转换：
	strData = String.fromCharCode.apply(null, new Uint16Array(data));
	return strData;
}
let fetchType=[
        {//自由文本
            req: 'type.googleapis.com/iyoudoctor.ai.v1.assist.FreeText',
            res: 'type.googleapis.com/iyoudoctor.ai.v1.assist.FreeText.Response',
            type:'FreeText'
        },{// 文本内容
            req: 'type.googleapis.com/iyoudoctor.ai.v1.assist.PlainText',
            type:'PlainText'
        },{ //机器人气泡显示图片
            req:'type.googleapis.com/iyoudoctor.ai.v1.assist.Image',
            type:'Image'
        },{// 文字单选
            req: 'type.googleapis.com/iyoudoctor.ai.v1.assist.TextOptions',
            res: 'type.googleapis.com/iyoudoctor.ai.v1.assist.TextOptions.Response',
            type:'TextOptions'
        },{// 图片单选
            req: 'type.googleapis.com/iyoudoctor.ai.v1.assist.ImageOptions',
            res: 'type.googleapis.com/iyoudoctor.ai.v1.assist.ImageOptions.Response',
            type:'ImageOptions'
        },{//化验选项
            req:'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquiryAskLabItemOptions',
            res:'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquiryAskLabItemOptions.Response',
            type:'AskLabItemOptions'
        },{//询问症状（输入或进入列表选择）
            req:'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquiryAskSymptoms',
            res:'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquiryAskSymptoms.Response',
            type:'AskSymptoms'
        },{//诊断结果
            req:'type.googleapis.com/iyoudoctor.ai.v1.doctor.Diagnosis',
            res:'type.googleapis.com/iyoudoctor.ai.v1.doctor.Diagnosis.Response',
            type:'Diagnosis'
        }, {//保存记录
            req: 'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquirySaveOptions',
            res: 'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquirySaveOptions.Response',
            type: 'SaveOptions'
        },{//基本信息
        		req: 'type.googleapis.com/iyoudoctor.ai.v1.assist.BasicInfoOptions',
            res: 'type.googleapis.com/iyoudoctor.ai.v1.assist.BasicInfoOptions.Response',
            type: 'BasicInfoOptions'
        },{//其他症状
        		req: 'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquiryAskOtherSymptomOptions',
            res: 'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquiryAskOtherSymptomOptions.Response',
            type: 'DoctorInquiryAskOtherSymptomOptions'
        },{//输入属性
        		req: 'type.googleapis.com/iyoudoctor.ai.v1.assist.TextWithButton',
            res: 'type.googleapis.com/iyoudoctor.ai.v1.assist.TextWithButton.Response',
            type: 'TextWithButton'
        },
        {//追问症状
        		req: 'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquiryAskSymptomAttrOptions',
            res: 'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquiryAskSymptomAttrOptions.Response',
            type: 'DoctorInquiryAskSymptomAttrOptions'
        },
        {//追问其他症状
        		req: 'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquiryAskOtherSymptomOptions',
            res: 'type.googleapis.com/iyoudoctor.ai.v1.assist.DoctorInquiryAskOtherSymptomOptions.Response',
            type: 'DoctorInquiryAskOtherSymptomOptions'
        },
        {//危机信息
        		req: 'type.googleapis.com/iyoudoctor.ai.v1.doctor.Notification',
            res: 'type.googleapis.com/iyoudoctor.ai.v1.doctor.Notification.Response',
            type: 'Notification'
        }
    ]
//将动态数据按照症状结构体组装页面结构
function buildSymptom(data, loadCommonSymptom,arrSelect){
	console.log(arrSelect,'arr')
	let _tempList = {}, _list = [],
	_sort=data.categories,
	_listSpe=[],	
	//_sort = ['头部', '咽喉和颈部', '四肢症状', '胸部', '腹部', '腰背部', '泌尿生殖', '臀部及肛门', '皮肤', '全身症状', '神经系统', '消化'],
    arr = [];
    data.items.map(function (val, idx) {
        let json = {};
        json.id = val.id;
        json.name = val.name;
        json.category = val.category;		
        json.checked = false;

        if (val.isCommon) {
            json.commonWeight = val.commonWeight || 0;
            arr.push(json);
        }
        if(val.notification){
      		json.notification = val.notification;
            arr.push(json);
        }
        if (_tempList[val.category]) {
            _tempList[val.category].push(json);
        } else {
            _tempList[val.category] = [];
            _tempList[val.category].push(json);
        }
    });
       
    //将左侧_sort分类通过weight于右侧list建立连接关系
    let _listKey = 0;
    for(var sKey in _sort){
    		var sortName = _sort[sKey].name;
    		for(let lKey in _tempList){   			
    			if(lKey == sortName){
    				_list[_listKey] = _tempList[lKey];
    				_listKey++;
    				break;
    			}
    		}
    }
    //处理常用症状
	let _commonZ = [];
    for(var sKey in data.bodySystems){
    		let sonList = [];
    		for(var sonKey in data.bodySystems[sKey].symptomIds){
    			sonList.push({
	    			category:"常用症状",
				checked:false,
				commonWeight:99,
				id:data.bodySystems[sKey].symptomIds[sonKey],
				name:data.bodySystems[sKey].symptomIds[sonKey]
			});
    		}
    		_commonZ.push({name:data.bodySystems[sKey].name, isCommonZ:true, sonList:sonList});
    }
    //默认加载常见症状分类，点击其他分类不需要展示
    if(true === loadCommonSymptom){
    		 _sort.unshift({name:'常见症状', weight:9999});
    }
    if(_commonZ){
    		//“常见症状”默认展示在第一个元素中，所以需要每次点击category时临时绑定左侧第一个对应元素
    		if(arrSelect){
    			arrSelect.map(function(val,index){
    				_commonZ.map(function(valCom,indexCom){
    					valCom.sonList.map(function(valSon,indexSon){
    						if(val.id==valSon.id){
    							_commonZ[indexCom].sonList[indexSon].checked=true;
    							return;
    						}
    					});
    				});
    			});
    		}
    		_list.unshift(_commonZ);
    }  
	return { _list, _sort };
}

//处理数据
function handleDialogueSucCb(data){
    let { talk } = data,
        _data = talk || data,
        { contents, asking, actions } = _data,
        _list = {
            id:data.id ||'',
            sn: _data.sn
        },
        _asking = {},
        _options = [],
        _action = [],
        _optType,
        age, gender, _diseases,
        _recall = {
            recall: {},
            isRecall: false
        }, _askName;
    if (asking && JSON.stringify(asking) != '{}') {
        _asking.type = asking['@type'];
        _optType = setType(asking['@type']);
       _list.optType = _optType;   
        if (asking.text) {
            _list[_list.length - 1].text = asking.text;
        }
        if (asking.options && asking.options.length > 0) {
            _asking.options = asking.options;
            _options = asking.options;
        }
		if (asking.options && asking.options.title ) {
            _asking.options.title = asking.options.title;
            _options.title = asking.options.title;
        }		
        if (asking.watermark) {
            _asking.watermark = asking.watermark;
        }
  
        if (_optType == 'AskSymptoms') {
            age = asking.age.year;
            gender = asking.gender;            
        }		
        // 保存结果
        if (_optType == 'SaveOptions') {
            let options = [
                { key: 'save', text: '确定' },
                { key: 'noSave', text: '取消' },
            ]

            _asking.options=options;
            _options=options;
            _asking.type='SaveOptions';
            if(asking.askName){
            		_asking.askName=asking.askName;
            }            
            _askName=asking.askName;
        }

        _list.asking = _asking;
    }

    if (contents && contents.length > 0) {
        let len = _data.contents.length,
            stems = [];

        contents.map((val, idx) => {
            let _optType = setType(val['@type']);          
            let json = {
                type: _optType,
                stem: val.text || '',
               
            };
			
			if(_optType=='TextWithButton'){
				json.type=val.type;
				json.buttonText=val.buttonText;
			}
            if (_optType =='Image'){
                json.stem=val.image
            }

            // 诊断结果
            if (_optType == 'Diagnosis') {           	
                if (val.items && val.items.length > 0) {    //有诊断结果

                    let arr=val.items.map(value=>{
                        let obj={
                            id: value.disease.id || '',
                            text: value.disease.name || '',
                            weight: value.weight || '',
                            describe: value.wikiAbstract || '',
                        }
                        if(value.department){
                            obj.departmentId=value.department.id || '';
                            obj.departmentName = value.department.text || '';
                        }
                        
                        if (value.drugPlans && value.drugPlans.length>0 ){
                            obj.drugPlans = value.drugPlans
                        }else{
                            obj.drugPlans=[];
                        }

                        return obj;
                    })
                    json.disease=arr;
                    //判断是否大于3个
                    let startIdx = (json.disease.length-3) > 0 ? json.disease.length-3 : 3;
					for(var i=json.disease.length-1; i>=0; i--){
						if(i >= startIdx){
							json.disease.splice(startIdx, 1);
						}
					}
                    _diseases = json.disease;
                    json.hasDiagnose = true;
					

                } else {       
                	//没有诊断结果
                    json.stem = val.suggestion ? (val.suggestion.text ? val.suggestion.text : '') : '';
                    json.hasDiagnose = false;
                }

                if (val.recalledItems && val.recalledItems.length > 0 && val.notification) {
                    _recall = {
                        items: val.recalledItems,
                        notification: val.notification,
                        isRecall:true
                    };
                    json.recallInfo = {
                        title: val.notification.title || '',
                        text: val.notification.text || ''
                    };
                    json.isRecall=true;
                }
            }

            // 更多
            if (val.detail) {
                json.action = [{
                    type: 'action',
                    text: '更多',
                    detail: val.detail,
                    commandId: 'more'
                }]
            }
            
            stems.push(json);
            _list.stems = stems;
        })
    }

    if (actions && actions.length > 0) {
        actions.map(val => {
            let json = {
                type: 'action',
                text: val.text,
                commandId: val.command ? (val.command.id ? val.command.id : '') : ''
            }
            _action.push(json);
        })
    }

    if (_action.length > 0) {
        _list.stems[_list.stems.length - 1].action = _action;
        _list.stems[_list.stems.length - 1].finish = false;      //是否点击过这次对话的acton
    }

    _list.answer = [];
    if (age && gender) {
        return { _list, _options, age, gender };
    }

    let _diseaseResult;
    if (_diseases) {
        _diseaseResult={
            sn: _data.sn,
            diagnoses:_diseases,
            recall: _recall
        }
        return { _list, _options, _diseaseResult, _askName };
    }  
    return { _list, _options };
}

function setType(type) {
    let optType = '';
    for (let i = 0; i < fetchType.length; i++) {
        if (type == fetchType[i].req) {
            optType = fetchType[i].type;
            break;
        }
    }
    return optType;
}
function getTime(){ 
	let _presentTime='',
    		date = new Date(),  
    		year = date.getFullYear(),  
	    month = date.getMonth()+1,//js中是从0开始所以要加1  
	    day = date.getDate(),  
	    hour = date.getHours(),  
	    minute = date.getMinutes(),  
	    second = date.getSeconds();  
      
    _presentTime=year+'/'+month+'/'+day;
    return _presentTime
}  
//很关键
export { 
   unzip,
   buildSymptom,
   handleDialogueSucCb,
   fetchType,
   getTime
}
